package com.conversationboard.view;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.confirm.Confirm;
import com.conversationboard.formatter.DateFormatter;
import com.conversationboard.formatter.ImageHider;
import com.conversationboard.model.User;
import com.conversationboard.model.adminlog.AdminLogEntry;
import com.conversationboard.model.preferences.SiteNewPostsViewInfo;
import com.conversationboard.security.EncryptionException;

public class AdminLogDisplay {

	public static String display(User user, List<AdminLogEntry> log) throws SQLException, EncryptionException, IOException {

		StringBuilder buffer = new StringBuilder();
		Map<Integer, SiteNewPostsViewInfo> displayInfo = user.getPreferences().getSiteNewPostsViewInfo();

		buffer.append("<table class=\"table\"><tr class=\"header\"><td class=\"cell\">Timestamp</td><td class=\"cell\">Board</td><td class=\"cell\">Action</td><td class=\"cell\">Reason</td></tr>");

		String key = "";

		if (user.isAdmin()) {
			key = Confirm.getKey(user.getLoginId());
		}

		for (AdminLogEntry entry : log) {

			if (entry.isAuthorised(user)) {
				buffer.append("<tr class=\"row\">");
				buffer.append("<td class=\"cell\">" + DateFormatter.prettyPrint(entry.getTimestamp(), user) + "</td>");

				buffer.append("<td class=\"cell\"");

				if ((displayInfo != null) && displayInfo.get(entry.getBoardId()) != null) {
					buffer.append(" style=\"color: " + displayInfo.get(entry.getBoardId()).getColour() + "\">");
				} else {
					buffer.append("\">");
				}

				buffer.append(entry.getBoardName(user) + "</td>");
				
				String text = ImageHider.substituteImagesForLinks(entry.getAction(), user.isAdmin(), false, (!user.getPreferences().isShowImages()));
				
				buffer.append("<td class=\"cell\">" + text + "</td>");

				String reason = entry.getReason();

				if (reason == null) {
					reason = "";
				}

				buffer.append("<td class=\"cell\">" + reason);

				/* If you're an admin and you entered this item, let you edit the reason */

				if (user.isAdmin() && user.getLoginId().equalsIgnoreCase(entry.getLoginId())) {
					buffer.append("<form action=\"" + Configuration.getInstance().getRoot() + "/Admin/AdminUpdateAdminLogControllerServlet\" method=\"post\">" + key + "<input type=\"hidden\" name=\"id\" value=\"" + entry.getId() + "\" />" + "<input type=\"text\" class=\"smalltextbox\" name=\"reason\" value=\"" + reason + "\" /><input type=\"submit\" value=\"Update\" /></form>");
				}

				buffer.append("</td>");
				buffer.append("</tr>");
			}
		}

		buffer.append("</table>");

		return buffer.toString();
	}

}
